﻿using System.Windows.Forms;

namespace Borg.Framework
{
    internal class PlugComboBoxBinder
    {
        private readonly System.Windows.Forms.ComboBox _box;
        private readonly SlotInfo _slot;

        private PlugComboBoxBinder(SlotInfo slot, System.Windows.Forms.ComboBox box)
        {
            _slot = slot;
            _box = box;
        }

        private void Bind()
        {
            BindData();
            SetFormatter();
            BindSelection();
        }

        private void BindData()
        {
            IDataModel<PlugTypeInfo> model = new RegistredPlugsDataModel(_slot);
            _box.DataSource = new DataSourceAdapter<PlugTypeInfo>(model);
        }

        private void BindSelection()
        {
            var binding = CreateBinding();
            _box.DataBindings.Add(binding);
        }

        public static void BindSlotToBox(SlotInfo slot, System.Windows.Forms.ComboBox box)
        {
            new PlugComboBoxBinder(slot, box).Bind();
        }

        private Binding CreateBinding()
        {
            return new Binding(
                "SelectedIndex",
                new PlugSelectionController(
                    _slot, PlugAndSelectExtensionAction.PlugAndSelectExtension,
                    SelectedRegisteredTypeProvider.SelectedRegisteredTypeIndex),
                "SelectedIndex")
                       {
                           ControlUpdateMode = ControlUpdateMode.OnPropertyChanged,
                           DataSourceUpdateMode = DataSourceUpdateMode.OnPropertyChanged
                       };
        }

        private void SetFormatter()
        {
            var formatter = new PlugTypeFormatter();
            _box.Format += formatter.OnFormat;
        }
    }
}

